﻿using BLL;
using Newtonsoft.Json.Linq;
using System;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using Utility;
using Utility.Helper;

namespace Thksoft
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                var parms = Request.Params["parms"];
                switch (parms)
                {
                    case "CheckLogin":
                        CheckLogin();
                        return;

                    case "GetCheckLoginInfo":
                        GetCheckLoginInfo();
                        return;

                    case "GetModuleInfo":
                        GetModuleInfo();
                        break;

                    default:
                        break;
                }
            }
        }

        protected void CheckLogin()
        {
            var userBll = new Sys_UserBLL();
            var data = GetPostData();
            var result = new JObject();
            var userName = data["UserName"].ToObject<string>();
            var passWord = data["PassWord"].ToObject<string>();
            var ifCheck = data["IfCheck"].ToObject<bool>();
            result["Msg"] = "用户名不存在或者密码错误";
            result["Type"] = 0;
            var user = userBll.GetInfoByLogin(userName.ToUpper());
            if (user != null)
            {
                if (passWord == "" || userName == "")
                {
                    Content(JToken.FromObject(result).ToString(), "application/json", Encoding.UTF8);
                    return;
                }
                else
                {
                    string Password = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(passWord, "MD5");
                    if (user.USER_PWD != Password)
                    {
                        Content(JToken.FromObject(result).ToString(), "application/json", Encoding.UTF8);
                        return;
                    }
                }
                Session["SysUserInfo"] = user;
                userBll.UpdateLogin(true, user.USER_ID, user.USER_NAME);
                if (ifCheck)
                {
                    HttpCookie cok = new HttpCookie("Login", userName + "&" + passWord);
                    cok.Path = "/";
                    cok.Expires = DateTime.Now.AddMonths(1);

                    Response.AppendCookie(cok);
                }
                else if (Request.Cookies["Login"] != null)
                {
                    HttpCookie cok = Request.Cookies["Login"];
                    cok.Value = "&";
                    cok.Path = "/";
                    cok.Expires = DateTime.Now.AddDays(-1);
                    Response.AppendCookie(cok);
                }
                //在Cookie中存入加密的用户信息
                var userkeyCookie = new HttpCookie("USER_KEY", DESEncrypt.Encrypt(user.USER_ID.ToString() + "|" + DateTime.Now.AddMonths(1).ToString("yyyy-MM-dd HH:mm:ss")));
                userkeyCookie.Expires = DateTime.Now.AddMonths(1);
                Response.AppendCookie(userkeyCookie);
                result["Msg"] = "登录成功";
                result["Type"] = 1;
                result["Data"] = JToken.FromObject(user);
                Response.ContentType = "";
                Content(JToken.FromObject(result).ToString(), "application/json", Encoding.UTF8);
                return;
            }
            Content(JToken.FromObject(result).ToString(), "application/json", Encoding.UTF8);
        }

        /// <summary>
        /// 获取记住的登陆信息
        /// </summary>
        /// <returns></returns>
        protected void GetCheckLoginInfo()
        {
            var result = new JObject();
            result["Msg"] = "没有记住密码";
            result["Type"] = 0;
            if (Request.Cookies["Login"] == null)
            {
                Content(JToken.FromObject(result).ToString(), "application/json", Encoding.UTF8);
                return;
            }
            result["Msg"] = "获取成功";
            result["Type"] = 1;
            var data = new JObject();
            result["Data"] = data;
            string Login = Request.Cookies["Login"].Value;
            data["UserName"] = Login.Split('&')[0].ToString();
            data["PassWord"] = Login.Split('&')[1].ToString();
            Content(JToken.FromObject(result).ToString(), "application/json", Encoding.UTF8);
            return;
        }

        protected void GetModuleInfo()
        {
            var user = new BaseBLL().User;
            var sql = @"SELECT
	T1.MODULE_ID,
	T1.MODULE_NAME,
	T1.MODULE_PATH,
	T1.MODULE_PARENTID,
	T1.MODULE_ORDERNUM1,
	T1.MODULE_ORDERNUM2
FROM
	SYS_MODULE T1 INNER JOIN SYS_ROLEMODULE T2 ON T1.MODULE_ID = T2.MODULE_ID
WHERE
	T2.ROLE_ID IN ({0}) AND
  T1.MODULE_STATE = 1
GROUP BY
	T1.MODULE_ID,
	T1.MODULE_NAME,
	T1.MODULE_PATH,
	T1.MODULE_PARENTID,
	T1.MODULE_ORDERNUM1,
	T1.MODULE_ORDERNUM2
ORDER BY
	T1.MODULE_ORDERNUM1 ASC,
	T1.MODULE_ORDERNUM2 ASC";
            var dt = new Sys_ModuleBLL().Query(string.Format(sql, user.USER_ROLEID));
            var arry = new JArray();
            foreach (var row in dt.AsEnumerable())
            {
                var obj = new JObject();
                arry.Add(obj);
                obj["ID"] = row.GetValue<int>("MODULE_ID");
                obj["NAME"] = row.GetValue<string>("MODULE_NAME");
                obj["PATH"] = row.GetValue<string>("MODULE_PATH");
                obj["PID"] = row.GetValue<string>("MODULE_PARENTID");
            }
            AjaxResult.Success(this.Context, arry);
            return;
        }

        protected JObject GetPostData()
        {
            var jsonStr = "";
            using (var steam = new StreamReader(Request.InputStream))
            {
                jsonStr = steam.ReadToEnd();
            }
            return JObject.Parse(jsonStr);
        }

        protected void Content(string content, string contentType, Encoding endcoding)
        {
            Response.HeaderEncoding = endcoding;
            Response.ContentType = contentType;
            Response.Write(content);
            Response.Flush();
            Response.End();
        }
    }
}